Admins can deactivate user accounts

Dominik Sander 8 years ago
parent
commit
8508928943

+ 19 - 1
app/controllers/admin/users_controller.rb

@@ -1,7 +1,7 @@
1 1
 class Admin::UsersController < ApplicationController
2 2
   before_action :authenticate_admin!
3 3
 
4
-  before_action :find_user, only: [:edit, :destroy, :update]
4
+  before_action :find_user, only: [:edit, :destroy, :update, :deactivate, :activate]
5 5
 
6 6
   helper_method :resource
7 7
 
@@ -64,6 +64,24 @@ class Admin::UsersController < ApplicationController
64 64
     end
65 65
   end
66 66
 
67
+  def deactivate
68
+    @user.deactivate!
69
+
70
+    respond_to do |format|
71
+      format.html { redirect_to admin_users_path, notice: "User '#{@user.username}' was deactivated." }
72
+      format.json { render json: @user, status: :ok, location: admin_users_path(@user) }
73
+    end
74
+  end
75
+
76
+  def activate
77
+    @user.activate!
78
+
79
+    respond_to do |format|
80
+      format.html { redirect_to admin_users_path, notice: "User '#{@user.username}' was activated." }
81
+      format.json { render json: @user, status: :ok, location: admin_users_path(@user) }
82
+    end
83
+  end
84
+
67 85
   private
68 86
 
69 87
   def find_user

+ 13 - 0
app/helpers/users_helper.rb

@@ -0,0 +1,13 @@
1
+module UsersHelper
2
+  def user_account_state(user)
3
+    if !user.active?
4
+      content_tag :span, 'inactive', class: 'label label-danger'
5
+    elsif user.access_locked?
6
+      content_tag :span, 'locked', class: 'label label-danger'
7
+    elsif ENV['REQUIRE_CONFIRMED_EMAIL'] == 'true' && !user.confirmed?
8
+      content_tag :span, 'unconfirmed', class: 'label label-warning'
9
+    else
10
+      content_tag :span, 'active', class: 'label label-success'
11
+    end
12
+  end
13
+end

+ 4 - 4
app/models/agent.rb

@@ -61,8 +61,8 @@ class Agent < ActiveRecord::Base
61 61
   has_many :scenario_memberships, :dependent => :destroy, :inverse_of => :agent
62 62
   has_many :scenarios, :through => :scenario_memberships, :inverse_of => :agents
63 63
 
64
-  scope :active,   -> { where(disabled: false) }
65
-  scope :inactive, -> { where(disabled: true) }
64
+  scope :active,   -> { where(disabled: false, deactivated: false) }
65
+  scope :inactive, -> { where(['disabled = ? OR deactivated = ?', true, true]) }
66 66
 
67 67
   scope :of_type, lambda { |type|
68 68
     type = case type
@@ -381,7 +381,7 @@ class Agent < ActiveRecord::Base
381 381
                 joins("JOIN links ON (links.receiver_id = agents.id)").
382 382
                 joins("JOIN agents AS sources ON (links.source_id = sources.id)").
383 383
                 joins("JOIN events ON (events.agent_id = sources.id AND events.id > links.event_id_at_creation)").
384
-                where("NOT agents.disabled AND (agents.last_checked_event_id IS NULL OR events.id > agents.last_checked_event_id)")
384
+                where("NOT agents.disabled AND NOT agents.deactivated AND (agents.last_checked_event_id IS NULL OR events.id > agents.last_checked_event_id)")
385 385
         if options[:only_receivers].present?
386 386
           scope = scope.where("agents.id in (?)", options[:only_receivers])
387 387
         end
@@ -432,7 +432,7 @@ class Agent < ActiveRecord::Base
432 432
     # per type of agent, so you can override this to define custom bulk check behavior for your custom Agent type.
433 433
     def bulk_check(schedule)
434 434
       raise "Call #bulk_check on the appropriate subclass of Agent" if self == Agent
435
-      where("agents.schedule = ? and disabled = false", schedule).pluck("agents.id").each do |agent_id|
435
+      where("NOT disabled AND NOT deactivated AND schedule = ?", schedule).pluck("agents.id").each do |agent_id|
436 436
         async_check(agent_id)
437 437
       end
438 438
     end

+ 26 - 0
app/models/user.rb

@@ -43,6 +43,32 @@ class User < ActiveRecord::Base
43 43
     end
44 44
   end
45 45
 
46
+  def active?
47
+    !deactivated_at
48
+  end
49
+
50
+  def deactivate!
51
+    User.transaction do
52
+      agents.update_all(deactivated: true)
53
+      update_attribute(:deactivated_at, Time.now)
54
+    end
55
+  end
56
+
57
+  def activate!
58
+    User.transaction do
59
+      agents.update_all(deactivated: false)
60
+      update_attribute(:deactivated_at, nil)
61
+    end
62
+  end
63
+
64
+  def active_for_authentication?
65
+    super && active?
66
+  end
67
+
68
+  def inactive_message
69
+    active? ? super : :deactivated_account
70
+  end
71
+
46 72
   def self.using_invitation_code?
47 73
     ENV['SKIP_INVITATION_CODE'] != 'true'
48 74
   end

+ 7 - 2
app/views/admin/users/index.html.erb

@@ -14,7 +14,7 @@
14 14
             <th>Email</th>
15 15
             <th>State</th>
16 16
             <th>Active agents</th>
17
-            <th>Inactive agents</th>
17
+            <th>Deactivated agents</th>
18 18
             <th>Registered since</th>
19 19
             <th>Options</th>
20 20
           </tr>
@@ -23,12 +23,17 @@
23 23
             <tr>
24 24
               <td><%= link_to user.username, edit_admin_user_path(user) %></td>
25 25
               <td><%= user.email %></td>
26
-              <td>state</td>
26
+              <td><%= user_account_state(user) %></td>
27 27
               <td><%= user.agents.active.count %></td>
28 28
               <td><%= user.agents.inactive.count %></td>
29 29
               <td title='<%= user.created_at %>'><%= time_ago_in_words user.created_at %> ago</td>
30 30
               <td>
31 31
                 <div class="btn-group btn-group-xs">
32
+                  <% if user.active? %>
33
+                    <%= link_to 'Deactivate', deactivate_admin_user_path(user), method: :put, class: "btn btn-default" %>
34
+                  <% else %>
35
+                    <%= link_to 'Activate', activate_admin_user_path(user), method: :put, class: "btn btn-default" %>
36
+                  <% end %>
32 37
                   <%= link_to 'Delete', admin_user_path(user), method: :delete, data: { confirm: 'Are you sure? This can not be undone.' }, class: "btn btn-default" %>
33 38
                 </div>
34 39
               </td>

+ 3 - 0
config/locales/en.yml

@@ -2,6 +2,9 @@
2 2
 # See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
3 3
 
4 4
 en:
5
+  devise:
6
+    failure:
7
+      deactivated_account: "Your account has been deactivated by an administrator."
5 8
   datetime:
6 9
     distance_in_words:
7 10
       half_a_minute: "half a minute"

+ 6 - 1
config/routes.rb

@@ -67,7 +67,12 @@ Huginn::Application.routes.draw do
67 67
   end
68 68
 
69 69
   namespace :admin do
70
-    resources :users, except: :show
70
+    resources :users, except: :show do
71
+      member do
72
+        put :deactivate
73
+        put :activate
74
+      end
75
+    end
71 76
   end
72 77
 
73 78
   get "/worker_status" => "worker_status#show"

+ 7 - 0
db/migrate/20160302095413_add_deactivated_at_to_users.rb

@@ -0,0 +1,7 @@
1
+class AddDeactivatedAtToUsers < ActiveRecord::Migration
2
+  def change
3
+    add_column :users, :deactivated_at, :datetime
4
+
5
+    add_index :users, :deactivated_at
6
+  end
7
+end

+ 6 - 0
db/migrate/20160307084729_add_deactivated_to_agents.rb

@@ -0,0 +1,6 @@
1
+class AddDeactivatedToAgents < ActiveRecord::Migration
2
+  def change
3
+    add_column :agents, :deactivated, :boolean, default: false
4
+    add_index :agents, [:disabled, :deactivated]
5
+  end
6
+end

+ 20 - 0
spec/features/admin_users_spec.rb

@@ -78,5 +78,25 @@ describe Admin::UsersController do
78 78
         expect(page).to have_text("Password confirmation doesn't match")
79 79
       end
80 80
     end
81
+
82
+    context "(de)activating users" do
83
+      it "deactivates an existing user" do
84
+        visit admin_users_path
85
+        expect(page).not_to have_text('inactive')
86
+        find(:css, "a[href='/admin/users/#{users(:bob).id}/deactivate']").click
87
+        expect(page).to have_text('inactive')
88
+        users(:bob).reload
89
+        expect(users(:bob)).not_to be_active
90
+      end
91
+
92
+      it "deactivates an existing user" do
93
+        users(:bob).deactivate!
94
+        visit admin_users_path
95
+        find(:css, "a[href='/admin/users/#{users(:bob).id}/activate']").click
96
+        expect(page).not_to have_text('inactive')
97
+        users(:bob).reload
98
+        expect(users(:bob)).to be_active
99
+      end
100
+    end
81 101
   end
82 102
 end

+ 41 - 0
spec/models/agent_spec.rb

@@ -3,6 +3,34 @@ require 'rails_helper'
3 3
 describe Agent do
4 4
   it_behaves_like WorkingHelpers
5 5
 
6
+  describe '.active/inactive' do
7
+    let(:agent) { agents(:jane_website_agent) }
8
+
9
+    it 'is active per default' do
10
+      expect(Agent.active).to include(agent)
11
+      expect(Agent.inactive).not_to include(agent)
12
+    end
13
+
14
+    it 'is not active when disabled' do
15
+      agent.update_attribute(:disabled, true)
16
+      expect(Agent.active).not_to include(agent)
17
+      expect(Agent.inactive).to include(agent)
18
+    end
19
+
20
+    it 'is not active when deactivated' do
21
+      agent.update_attribute(:deactivated, true)
22
+      expect(Agent.active).not_to include(agent)
23
+      expect(Agent.inactive).to include(agent)
24
+    end
25
+
26
+    it 'is not active when disabled and deactivated' do
27
+      agent.update_attribute(:disabled, true)
28
+      agent.update_attribute(:deactivated, true)
29
+      expect(Agent.active).not_to include(agent)
30
+      expect(Agent.inactive).to include(agent)
31
+    end
32
+  end
33
+
6 34
   describe ".bulk_check" do
7 35
     before do
8 36
       @weather_agent_count = Agents::WeatherAgent.where(:schedule => "midnight", :disabled => false).count
@@ -18,6 +46,12 @@ describe Agent do
18 46
       mock(Agents::WeatherAgent).async_check(anything).times(@weather_agent_count - 1)
19 47
       Agents::WeatherAgent.bulk_check("midnight")
20 48
     end
49
+
50
+    it "should skip agents of deactivated accounts" do
51
+      agents(:bob_weather_agent).user.deactivate!
52
+      mock(Agents::WeatherAgent).async_check(anything).times(@weather_agent_count - 1)
53
+      Agents::WeatherAgent.bulk_check("midnight")
54
+    end
21 55
   end
22 56
 
23 57
   describe ".run_schedule" do
@@ -335,6 +369,13 @@ describe Agent do
335 369
           Agent.receive! # and we receive it
336 370
         }.to change { agents(:bob_rain_notifier_agent).reload.last_checked_event_id }
337 371
       end
372
+
373
+      it "should not run agents of deactivated accounts" do
374
+        agents(:bob_weather_agent).user.deactivate!
375
+        Agent.async_check(agents(:bob_weather_agent).id)
376
+        mock(Agent).async_receive(agents(:bob_rain_notifier_agent).id, anything).times(0)
377
+        Agent.receive!
378
+      end
338 379
     end
339 380
 
340 381
     describe ".async_receive" do

+ 24 - 0
spec/models/users_spec.rb

@@ -40,4 +40,28 @@ describe User do
40 40
       end
41 41
     end
42 42
   end
43
+
44
+  context '#deactivate!' do
45
+    it "deactivates the user and all her agents" do
46
+      agent = agents(:jane_website_agent)
47
+      users(:jane).deactivate!
48
+      agent.reload
49
+      expect(agent.deactivated).to be_truthy
50
+      expect(users(:jane).deactivated_at).not_to be_nil
51
+    end
52
+  end
53
+
54
+  context '#activate!' do
55
+    before do
56
+      users(:bob).deactivate!
57
+    end
58
+
59
+    it 'activates the user and all his agents' do
60
+      agent = agents(:bob_website_agent)
61
+      users(:bob).activate!
62
+      agent.reload
63
+      expect(agent.deactivated).to be_falsy
64
+      expect(users(:bob).deactivated_at).to be_nil
65
+    end
66
+  end
43 67
 end